package com.csc775.gui;

import java.io.IOException;
import java.io.OptionalDataException;

import com.csc775.AndroidWalkieTalkieActivity;
import com.csc775.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.csc775.message.ControlMessage;
import com.csc775.message.ControlRquestType;
import com.csc775.networking.Client;

public class LoginActivity extends Activity {

	EditText username;                                   // textbox for username
	EditText password;                                   // textbox for password
	EditText re_password;                               // textbox for re-entering password
	
	private static Client client = null;                 // client to send message

	/**
	 * static method to get client
	 * 
	 * @return
	 */
	public static Client getClient() {
		return client;
	}

	/**
	 * static method to set client
	 * 
	 * @param client
	 */
	public static void setClient(Client client) {
		LoginActivity.client = client;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registration);
		username = (EditText) findViewById(R.id.userName_TextBox);
		password = (EditText) findViewById(R.id.password_TextBox);
		re_password = (EditText) findViewById(R.id.rePassword_TextBox);
		Button register = (Button) findViewById(R.id.RegisterButton);
		re_password.setInputType(0);
		register.setOnClickListener(new View.OnClickListener() {
			@Override
			/**
			 * executes when the register button is clicked
			 */
			public void onClick(View view) {

				Log.v("EditText", username.getText().toString());
				Log.v("EditText", password.getText().toString());
				Log.v("EditText", re_password.getText().toString());
				// checks if the fields are not null
				if (username.getText().toString().isEmpty()   
						|| password.getText().toString().isEmpty()
						|| re_password.getText().toString().isEmpty()) {

					Toast toast = Toast.makeText(getApplicationContext(),
							"Please enter user credential.", Toast.LENGTH_LONG);
					toast.show();
					return;
				}
				if (password.getText().toString()
						.equals(re_password.getText().toString())) {

					// current username of the user logged in
					AndroidWalkieTalkieActivity.currentUserName = username
							.getText().toString();                     
			        Context context = getApplicationContext();

					StringBuffer buf = new StringBuffer();
					buf.append(username.getText().toString());
					buf.append("~");
					buf.append(password.getText().toString());

					ControlMessage msg = new ControlMessage(
							AndroidWalkieTalkieActivity.serverIP,
							AndroidWalkieTalkieActivity.serverPort, buf
									.toString().length(), buf.toString());// creates a control message
					msg.setRequestType(ControlRquestType.REGISTER); // sets the request type

					client = new Client();
					if (client.run()) {
						client.Sendmessage(msg.toString());// client sends the message to server
						{
							try {
								String str = (String) client.getOis()
										.readObject();// client receives the message

								ControlMessage msgObj = ControlMessage
										.getControlMessageInstance(str);
								int type = msgObj.getRequestType();

								switch (type) {

								case ControlRquestType.REGISTER_ACK:
									if (msgObj.getExtraData().equals("INVALID_USER")) { //checks the ack sent by the server
										Toast toast1 = Toast
												.makeText(
														getApplicationContext(),
														"Username already exists\nPlease select a different username.",
														Toast.LENGTH_LONG);
										toast1.show();
										username.setText("");
										password.setText("");
										re_password.setText("");
										return;
									} //successfully registered
									else {
										// This will change the activity to handle groups
										AndroidWalkieTalkieActivity.currentUserName = username
												.getText().toString();
										Intent myIntent = new Intent(view.getContext(),GroupChooseActivity.class);
										startActivityForResult(myIntent, 0);
										finish();
									}
								default:
								}
							} catch (OptionalDataException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ClassNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					} else {
						// this will display toast if the centralized server is down
						Toast toast1 = Toast.makeText(getApplicationContext(),
								"Service discovery server in down!",
								Toast.LENGTH_LONG);
						toast1.show();
					}
				}
				finish(); //finishes the current activity
			}
		});
		/**
		 * this function gets invoked on pressing cancel button
		 */
		Button cancel = (Button) findViewById(R.id.cancelButton);                 
		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent();
				setResult(RESULT_OK, intent);
				// go to previous activity
				Intent myIntent = new Intent(view.getContext(),
						AndroidWalkieTalkieActivity.class);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});
	}

}